package com.tl.sun.ui.fragment.model;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.blankj.utilcode.utils.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.tl.sun.AppContext;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.event.AddEtEnvent;
import com.tl.sun.event.CityEvent;
import com.tl.sun.event.ClickEvent;
import com.tl.sun.event.CollectEvent;
import com.tl.sun.event.LineEvent;
import com.tl.sun.helper.UIHelper;
import com.tl.sun.manager.MDModel;
import com.tl.sun.model.CollectUse;
import com.tl.sun.model.IpModelEntity;
import com.tl.sun.model.IpUseEntity;
import com.tl.sun.model.ModelCity;
import com.tl.sun.model.ModelLine;
import com.tl.sun.model.TimeEntity;
import com.tl.sun.model.base.BaseEntity;
import com.tl.sun.ui.adapter.IpCityAdapter;
import com.tl.sun.ui.adapter.IpModelAdapter;
import com.tl.sun.ui.adapter.IpTimeAdapter;
import com.tl.sun.ui.adapter.IpUseAdapter;
import com.tl.sun.utils.ToastUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：HQY on 17/8/7 10:16
 * 邮箱：hqy_xz@126.com
 */

public class CollectModelFragment extends Fragment {


    @Bind(R.id.tv_model_use)
    TextView mTvModelUse;
    @Bind(R.id.tv_model_time)
    TextView mTvModelTime;
    @Bind(R.id.tv_model_address)
    TextView mTvModelAddress;

    @Bind(R.id.rv_ip_list)
    RecyclerView mRvIpList;
    @Bind(R.id.rv_ipuse_list)
    RecyclerView mRvIpuseList;
    @Bind(R.id.rl_ip_use)
    RelativeLayout mRlIpUse;
    @Bind(R.id.ll_ip_top)
    LinearLayout mLlIpTop;
    @Bind(R.id.rv_time_list)
    RecyclerView mRvTimeList;
    @Bind(R.id.rl_ip_time)
    RelativeLayout mRlIpTime;
    @Bind(R.id.ll_ip_address)
    LinearLayout mLlIpAddress;
    @Bind(R.id.tv_address_unspecified)
    TextView mTvAddressUnspecified;
    @Bind(R.id.iv_address_unspecified)
    ImageView mIvAddressUnspecified;
    @Bind(R.id.tv_address_specify)
    TextView mTvAddressSpecify;
    @Bind(R.id.rv_address_list)
    RecyclerView mRvAddressList;
    @Bind(R.id.iv_address_add)
    ImageView mIvAddressAdd;
    @Bind(R.id.ll_address_city)
    LinearLayout mLlAddressCity;
    @Bind(R.id.rv_shield_list)
    RecyclerView mRvShieldList;
    @Bind(R.id.iv_shield_add)
    ImageView mIvShieldAdd;
    @Bind(R.id.ll_shield_city)
    LinearLayout mLlShieldCity;
    @Bind(R.id.iv_address_specify)
    ImageView mIvAddressSpecify;
    @Bind(R.id.tv_address_screen)
    TextView mTvAddressScreen;
    @Bind(R.id.iv_address_screen)
    ImageView mIvAddressScreen;
    @Bind(R.id.sv_ip_list)
    SpringView mSvIpList;


    private String model;
    private View rootView;
    private boolean isUse = true;
    private boolean isTime = true;
    private boolean isAddress = true;
    private List<IpUseEntity> mIpUseList = new ArrayList<>();
    private IpUseAdapter mIpUseAdapter;

    private List<TimeEntity> mTimeList = new ArrayList<>();
    private IpTimeAdapter mIpTimeAdapter;


    private ArrayList<ModelCity> mIpCityList = new ArrayList<>();
    private IpCityAdapter mIpCityAdapter;

    private List<IpModelEntity> mIpModelList = new ArrayList<>();
    private IpModelAdapter mIpModelAdapter;
    private int number = 1;
    private int ipArea;
    private int ipExpire;
    private int ipUsed;
    private String cityList;
    private String groupId;
    private IpModelEntity mIpModel;
    private String modelType;

    public static CollectModelFragment newInstance(String title) {

        Bundle args = new Bundle();
        args.putString(UIHelper.MODEL, title);
        CollectModelFragment fragment = new CollectModelFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (EmptyUtils.isNotEmpty(getArguments())) {
            model = getArguments().getString(UIHelper.MODEL);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_model_two, container, false);
            ButterKnife.bind(this, rootView);
            showView();
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }


    private void showView() {
        ipUsed = MDModel.getInstance().getIpUsedTwo();
        ipExpire = MDModel.getInstance().getIpExpireTwo();
        ipArea = MDModel.getInstance().getIpAreaTwo();
        getIPUse(Integer.valueOf(ipUsed));
        mTvModelUse.setText(mIpUseList.get(Integer.valueOf(ipUsed)).getName());
        getTime(ipExpire);
        mTvModelTime.setText(mTimeList.get(ipExpire).getName());
        setCity(ipArea + "", "2");
        if (ipArea == 0) {
            mTvModelAddress.setText("IP归属地");
        } else if (ipArea == 1) {
            mTvModelAddress.setText("指定城市");
        } else if (ipArea == 2) {
            mTvModelAddress.setText("屏蔽城市");
        }
        getIpModel();
        getList();
    }

    private void getList() {
        mIpModelList.clear();
        if (model.equals("ip")) {
            modelType = "1";
            getIpList(ipArea, ipExpire, ipUsed, cityList);
        } else if (model.equals("collection")) {
            modelType = "3";
            getIpUseList("2", ipArea, ipExpire, ipUsed, cityList, groupId);
        } else if (model.equals("record")) {
            modelType = "2";
            getIpUseList("1", ipArea, ipExpire, ipUsed, cityList, groupId);
        }
    }

    @OnClick({R.id.tv_model_use, R.id.tv_model_time, R.id.tv_model_address, R.id.iv_use_bottom
            , R.id.iv_time_bottom, R.id.iv_address_bottom, R.id.rl_address_add, R.id.rl_shield_add
            , R.id.rl_address_unspecified, R.id.rl_address_specify, R.id.rl_address_screen})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_model_use:
                if (isUse) {
                    isUse = false;
                    isTime = true;
                    isAddress = true;
                    mTvModelUse.setTextColor(getActivity().getResources().getColor(R.color.main_text_check_color));
                    mRlIpUse.setVisibility(View.VISIBLE);
                    mTvModelTime.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                    mRlIpTime.setVisibility(View.GONE);
                    mTvModelAddress.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                    mLlIpAddress.setVisibility(View.GONE);
                } else {
                    isUse = true;
                    mTvModelUse.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                    mRlIpUse.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_model_time:
                if (isTime) {
                    isTime = false;
                    isUse = true;
                    isAddress = true;
                    mTvModelUse.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                    mRlIpUse.setVisibility(View.GONE);
                    mTvModelTime.setTextColor(getActivity().getResources().getColor(R.color.main_text_check_color));
                    mRlIpTime.setVisibility(View.VISIBLE);
                    mTvModelAddress.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                    mLlIpAddress.setVisibility(View.GONE);
                } else {
                    isTime = true;
                    mTvModelTime.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                    mRlIpTime.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_model_address:
                if (isAddress) {
                    isAddress = false;
                    isUse = true;
                    isTime = true;
                    mTvModelUse.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                    mRlIpUse.setVisibility(View.GONE);
                    mTvModelTime.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                    mRlIpTime.setVisibility(View.GONE);
                    mTvModelAddress.setTextColor(getActivity().getResources().getColor(R.color.main_text_check_color));
                    mLlIpAddress.setVisibility(View.VISIBLE);

                } else {
                    isAddress = true;
                    mTvModelAddress.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                    mLlIpAddress.setVisibility(View.GONE);
                }
                break;
//            IP归属地
            case R.id.rl_address_unspecified:
//                不指定
                setCity("0", "1");
                mTvModelAddress.setText("IP归属地");
                break;
            case R.id.rl_address_specify:
//                指定
                setCity("1", "1");
                mTvModelAddress.setText("指定城市");
                break;
            case R.id.rl_address_screen:
//                屏蔽
                setCity("2", "1");
                mTvModelAddress.setText("屏蔽城市");
                break;
            case R.id.rl_address_add:
                UIHelper.showAddressDialog(getActivity(), model, "1");
                break;
            case R.id.rl_shield_add:
                UIHelper.showAddressDialog(getActivity(), model, "2");
                break;
            case R.id.iv_use_bottom:
                isUse = true;
                mTvModelUse.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                mRlIpUse.setVisibility(View.GONE);
                break;
            case R.id.iv_time_bottom:
                isTime = true;
                mTvModelTime.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                mRlIpTime.setVisibility(View.GONE);
                break;
            case R.id.iv_address_bottom:
                isAddress = true;
                mTvModelAddress.setTextColor(getActivity().getResources().getColor(R.color.color_444444));
                mLlIpAddress.setVisibility(View.GONE);
                break;
        }
    }

    private void getIpModel() {
        mIpModelAdapter = new IpModelAdapter(mIpModelList);
        mRvIpList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvIpList.setAdapter(mIpModelAdapter);
        mRvIpList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                IpModelEntity ipModel = mIpModelList.get(position);
                EventBus.getDefault().post(new LineEvent(ipModel.getRegion(), ipModel.getCity(),
                        ipModel.getMark(), ipModel.getId(), ipModel.getAgreement(),
                        "2", new ModelLine(ipModel.getLineId(), modelType)));
                getActivity().finish();

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                mIpModel = mIpModelList.get(position);
                switch (view.getId()) {
                    case R.id.iv_model_more:
                        for (int i = 0; i < mIpModelList.size(); i++) {
                            if (i == position) {
                                mIpModelList.get(i).setShow(true);
                            } else {
                                mIpModelList.get(i).setShow(false);
                            }
                        }
                        mIpModelAdapter.notifyDataSetChanged();
                        break;
                    case R.id.rl_model_collect:
                        if (mIpModelList.get(position).getIsCollect() == 1) {
                            setLineStore("0", mIpModelList.get(position).getLineId(), mIpModel.getMark(), mIpModel.getGroupId());
                        } else {
//                            UIHelper.showCollectDialog(getActivity(), "1");
                            setLineStore("1", mIpModel.getLineId(), mIpModel.getMark(), "0");
                        }

                        setHideTime();
                        break;
                    case R.id.tv_model_note:
                        if (model.equals("collection")) {
                            UIHelper.showAddEtDialog(getActivity(), "2", mIpModel.getLineId());
                        }
                        break;
                }
            }
        });
        mRvIpList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                for (int i = 0; i < mIpModelList.size(); i++) {
                    mIpModelList.get(i).setShow(false);
                }
                mIpModelAdapter.notifyDataSetChanged();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        if (!model.equals("ip")) {
            mSvIpList.setType(SpringView.Type.FOLLOW);
            mSvIpList.setListener(new SpringView.OnFreshListener() {
                @Override
                public void onRefresh() {
                    number = 1;
                    mIpModelList.clear();
                    if (model.equals("record")) {
                        getIpUseList("1", ipArea, ipExpire, ipUsed, cityList, groupId);
                    } else {
                        getIpUseList("2", ipArea, ipExpire, ipUsed, cityList, groupId);
                    }
                }

                @Override
                public void onLoadmore() {
                    if (model.equals("record")) {
                        getIpUseList("1", ipArea, ipExpire, ipUsed, cityList, groupId);
                    } else {
                        getIpUseList("2", ipArea, ipExpire, ipUsed, cityList, groupId);
                    }
                }
            });
            mSvIpList.setHeader(new DefaultHeader(getActivity()));
            mSvIpList.setFooter(new DefaultHeader(getActivity()));
        }

    }

    private void setHideTime() {
        for (int i = 0; i < mIpModelList.size(); i++) {
            mIpModelList.get(i).setShow(false);
        }
        mIpModelAdapter.notifyDataSetChanged();
    }

    private void getIPUse(int num) {
        mIpUseList.clear();
        for (int i = 0; i < 5; i++) {
            IpUseEntity use = new IpUseEntity();
            if (i == 0) {
                use.setName("不过滤");
            } else if (i == 1) {
                use.setName("过滤近1天");
            } else if (i == 2) {
                use.setName("过滤近3天");
            } else if (i == 3) {
                use.setName("过滤近7天");
            } else if (i == 4) {
                use.setName("过滤近1个月");
            }
            if (i == num) {
                use.setShow(true);
            }
            mIpUseList.add(use);
        }
        mIpUseAdapter = new IpUseAdapter(mIpUseList);
        mRvIpuseList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvIpuseList.setAdapter(mIpUseAdapter);
        mRvIpuseList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                if (position == 0) {
                    mTvModelUse.setText("使用过的IP");
                } else {
                    mTvModelUse.setText(mIpUseList.get(position).getName());
                }
                for (int i = 0; i < mIpUseList.size(); i++) {
                    if (i == position) {
                        mIpUseList.get(i).setShow(true);
                    } else {
                        mIpUseList.get(i).setShow(false);
                    }
                }
                ipUsed = position;
                MDModel.getInstance().setIpUsedTwo(position);
                MDModel.getInstance().writeToCache();
                number = 1;
                getList();
                mIpUseAdapter.notifyDataSetChanged();
            }
        });
    }

    private void getTime(int num) {
        mTimeList.clear();
        for (int i = 0; i < 7; i++) {
            TimeEntity time = new TimeEntity();
            if (i == 0) {
                time.setName("全部");
            } else if (i == 1) {
                time.setName("5分钟");
            } else if (i == 2) {
                time.setName("30分钟");
            } else if (i == 3) {
                time.setName("1小时");
            } else if (i == 4) {
                time.setName("3小时");
            } else if (i == 5) {
                time.setName("6小时");
            } else if (i == 6) {
                time.setName("12小时");
            }
            if (i == num) {
                time.setShow(true);
            }
            mTimeList.add(time);
        }

        mIpTimeAdapter = new IpTimeAdapter(mTimeList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvTimeList.setLayoutManager(layoutManager);
        mRvTimeList.setAdapter(mIpTimeAdapter);
        mRvTimeList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == 0) {
                    mTvModelTime.setText("IP到期时间");
                } else {
                    mTvModelTime.setText(mTimeList.get(position).getName());
                }
                for (int i = 0; i < mTimeList.size(); i++) {
                    if (i == position) {
                        mTimeList.get(i).setShow(true);
                    } else {
                        mTimeList.get(i).setShow(false);
                    }
                }
                ipExpire = position;
                MDModel.getInstance().setIpExpireTwo(ipExpire);
                MDModel.getInstance().writeToCache();
                number = 1;
                getList();
                mIpTimeAdapter.notifyDataSetChanged();
            }


        });
    }

    private void setCity(String num, String type) {
        number = 1;
        ipArea = Integer.valueOf(num);
        MDModel.getInstance().setIpAreaTwo(Integer.valueOf(num));
        MDModel.getInstance().writeToCache();
        mTvAddressUnspecified.setTextColor(getActivity().getResources().getColor(num.equals("0") ? R.color.main_text_check_color : R.color.color_444444));
        mTvAddressSpecify.setTextColor(getActivity().getResources().getColor(num.equals("1") ? R.color.main_text_check_color : R.color.color_444444));
        mTvAddressScreen.setTextColor(getActivity().getResources().getColor(num.equals("2") ? R.color.main_text_check_color : R.color.color_444444));
        mIvAddressUnspecified.setVisibility(num.equals("0") ? View.VISIBLE : View.GONE);
        mIvAddressSpecify.setVisibility(num.equals("1") ? View.VISIBLE : View.GONE);
        mIvAddressScreen.setVisibility(num.equals("2") ? View.VISIBLE : View.GONE);
        number = 1;
        if (num.equals("1")) {
            mLlAddressCity.setVisibility(View.VISIBLE);
            mRvAddressList.setVisibility(View.VISIBLE);
            mLlShieldCity.setVisibility(View.GONE);
            mRvShieldList.setVisibility(View.GONE);
            getCity(type);
        } else if (num.equals("2")) {
            mLlAddressCity.setVisibility(View.GONE);
            mRvAddressList.setVisibility(View.GONE);
            mLlShieldCity.setVisibility(View.VISIBLE);
            mRvShieldList.setVisibility(View.VISIBLE);
            getShieldCity(type);
        } else {
            mLlShieldCity.setVisibility(View.GONE);
            mLlAddressCity.setVisibility(View.GONE);
            cityList = "0";
            if (type.equals("1")) {
                getList();
            }
        }
    }

    private void getCity(String type) {
        mIpCityList.clear();
        String mCityList = MDModel.getInstance().getCityList();
        Gson gson = new Gson();
        Type cityType = new TypeToken<List<ModelCity>>() {
        }.getType();
        if (EmptyUtils.isNotEmpty(mCityList)) {
            mIpCityList = gson.fromJson(mCityList, cityType);
        }

        if (mIpCityList.size() >= 3) {
            mIvAddressAdd.setVisibility(View.GONE);
        } else {
            mIvAddressAdd.setVisibility(View.VISIBLE);
        }
        mIpCityAdapter = new IpCityAdapter(mIpCityList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvAddressList.setLayoutManager(layoutManager);
        mRvAddressList.setAdapter(mIpCityAdapter);
        mRvAddressList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                //删除
                mIpCityList.remove(position);
                Logger.e("数量：" + mIpCityList.size() + "   " + position);
                Gson gson = new Gson();
                MDModel.getInstance().setCityList(gson.toJson(mIpCityList));
                MDModel.getInstance().writeToCache();
                number = 1;
                getCity("1");
            }
        });
        getCityList(type);
    }

    private void getCityList(String type) {
        List<Integer> mCity = new ArrayList<>();
        for (int i = 0; i < mIpCityList.size(); i++) {
            mCity.add(mIpCityList.get(i).getCityId());
        }
        Logger.e("数量" + mCity.size());
        if (mCity.size() == 0) {
            cityList = "0";
        } else {
            cityList = mCity.toString();
        }
        if (type.equals("1"))
            getList();
    }

    private void getShieldCity(String type) {
        mIpCityList.clear();
        String mCityList = MDModel.getInstance().getShieldCity();
        Gson gson = new Gson();
        Type cityType = new TypeToken<List<ModelCity>>() {
        }.getType();
        if (EmptyUtils.isNotEmpty(mCityList)) {
            mIpCityList = gson.fromJson(mCityList, cityType);
        }

        if (mIpCityList.size() >= 3) {
            mIvShieldAdd.setVisibility(View.GONE);
        } else {
            mIvShieldAdd.setVisibility(View.VISIBLE);
        }
        mIpCityAdapter = new IpCityAdapter(mIpCityList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvShieldList.setLayoutManager(layoutManager);
        mRvShieldList.setAdapter(mIpCityAdapter);
        mRvShieldList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemClick(adapter, view, position);
                //删除
                mIpCityList.remove(position);
                Logger.e("数量：" + mIpCityList.size() + "   " + position);
                Gson gson = new Gson();
                MDModel.getInstance().setShieldCity(gson.toJson(mIpCityList));
                MDModel.getInstance().writeToCache();
                number = 1;
                getShieldCity("1");
            }
        });
        getCityList(type);

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(AddEtEnvent event) {
        LogUtils.e("输入框：" + event.getType());
        if (event.getType().equals("1") && model.equals("ip")) {
            UIHelper.showAddEtDialog(getActivity(), "1", mIpModel.getLineId());
        } else if (event.getType().equals("2") && model.equals("collection")) {
            number = 1;
            mIpModelList.clear();
            getIpUseList("2", ipArea, ipExpire, ipUsed, cityList, groupId);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ClickEvent event) {
        number = 1;
        mIpModelList.clear();
        if (event.getType().equals("1") && model.equals("ip")) {
            Logger.e("1");
            getIpList(ipArea, ipExpire, ipUsed, cityList);
        } else if (event.getType().equals("2") && model.equals("collection")) {
            Logger.e("2");
            getIpUseList("2", ipArea, ipExpire, ipUsed, cityList, groupId);
        } else if (event.getType().equals("3") && model.equals("record")) {
            Logger.e("3");
            getIpUseList("1", ipArea, ipExpire, ipUsed, cityList, groupId);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CityEvent event) {
        if (model.equals(event.getType())) {
            if (event.getNum().equals("1")) {
                mIpCityList.clear();
                setCity(event.getmCity());
            } else {
                mIpCityList.clear();
                setShieldCity(event.getmCity());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CollectEvent event) {
        Logger.e("IP");
        if (event.getType().equals("1") && model.equals("ip")) {
            setLineStore("1", mIpModel.getLineId(), mIpModel.getMark(), event.getId() + "");
        } else if (event.getType().equals("2") && model.equals("collection")) {
            number = 1;
            mIpModelList.clear();
            groupId = event.getId() + "";
            getIpUseList("2", ipArea, ipExpire, ipUsed, cityList, groupId);
        }

    }

    /**
     * 添加指定城市
     *
     * @param modelCity
     */
    private void setCity(ModelCity modelCity) {
        String mCityList = MDModel.getInstance().getCityList();
        Gson gson = new Gson();
        Type cityType = new TypeToken<List<ModelCity>>() {
        }.getType();
        if (EmptyUtils.isNotEmpty(mCityList)) {
            mIpCityList = gson.fromJson(mCityList, cityType);
        }
        mIpCityList.add(modelCity);
        String str = gson.toJson(mIpCityList);
        MDModel.getInstance().setCityList(str);
        MDModel.getInstance().writeToCache();
        number = 1;
        getCity("1");
    }

    /**
     * 添加屏蔽城市
     *
     * @param modelCity
     */
    private void setShieldCity(ModelCity modelCity) {
        String mCityList = MDModel.getInstance().getShieldCity();
        Gson gson = new Gson();
        Type cityType = new TypeToken<List<ModelCity>>() {
        }.getType();
        if (EmptyUtils.isNotEmpty(mCityList)) {
            mIpCityList = gson.fromJson(mCityList, cityType);
        }
        mIpCityList.add(modelCity);
        String str = gson.toJson(mIpCityList);
        MDModel.getInstance().setShieldCity(str);
        MDModel.getInstance().writeToCache();
        number = 1;
        getShieldCity("1");
    }

    /**
     * 获取IP库列表
     *
     * @param ipArea
     * @param ipExpire
     * @param ipUsed
     * @param cityList
     */
    private void getIpList(int ipArea, int ipExpire, int ipUsed, String cityList) {
        Map<String, String> map = new HashMap<>();
        if (ipArea == 1 || ipArea == 2) {
            if (!cityList.equals("0")) {
                map.put("ip_area", ipArea + "");
            }
        }
        map.put("ip_expire", ipExpire + "");
        map.put("ip_used", ipUsed + "");
        map.put("city_list", cityList);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/ip_rand")
                .tag("ip")
                .params(map)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseEntity base = AppContext.getBaseEntity(s);
                        if (base.getRet() == 0) {
                            Gson gson = new Gson();
                            Type ipType = new TypeToken<BaseEntity<List<IpModelEntity>>>() {
                            }.getType();
                            BaseEntity<List<IpModelEntity>> baseModel = gson.fromJson(s, ipType);
                            mIpModelList = baseModel.getData();
                            mIpModelAdapter.setNewData(mIpModelList);
                        } else {
                            ToastUtil.showToast(base.getMsg());
                        }

                    }
                });

    }

    /**
     * 线路收藏
     *
     * @param isStore
     * @param lineId
     */
    private void setLineStore(String isStore, final String lineId, String ip, String groupId) {
        Map<String, String> map = new HashMap<>();
        map.put("is_stored", isStore);
        map.put("line_id", lineId);
        map.put("group_id", groupId);
        map.put("ip", ip);
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/line_store")
                .tag("ip")
                .params(map)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        BaseEntity base = AppContext.getBaseEntity(s);
                        if (base.getRet() == 0) {
//                            number = 1;
//                            mIpModelList.clear();
//                            getList();
                            for (int i = 0; i < mIpModelList.size(); i++) {
                                if (mIpModelList.get(i).getLineId().equals(lineId)) {
                                    mIpModelList.get(i).setIsCollect(0);
                                } else {
                                    mIpModelList.get(i).setIsCollect(1);
                                }
                            }
                            mIpModelAdapter.notifyDataSetChanged();
                            Logger.e("收藏：");
                        } else {
                            ToastUtil.showToast(base.getMsg());
                        }
                    }
                });

    }

    /**
     * 获取收藏和记录列表
     *
     * @param action
     * @param ipArea
     * @param ipExpire
     * @param ipUsed
     * @param cityList
     */
    private void getIpUseList(String action, int ipArea, int ipExpire, int ipUsed, String cityList, String groupId) {
        Map<String, String> map = new HashMap<>();
        map.put("action", action);
        if (ipArea == 1 || ipArea == 2) {
            if (!cityList.equals("0")) {
                map.put("ip_area", ipArea + "");
            }
        }
        map.put("ip_expire", ipExpire + "");
        map.put("ip_used", ipUsed + "");
        map.put("page", number + "");
        map.put("city_list", cityList);
        map.put("group_id", "0");
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "pond/ip_use_list")
                .tag("ip")
                .params(map)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        mSvIpList.onFinishFreshAndLoad();
                        BaseEntity base = AppContext.getBaseEntity(s);
                        if (base.getRet() == 0) {
                            Gson gson = new Gson();
                            Type useType = new TypeToken<BaseEntity<CollectUse>>() {
                            }.getType();
                            BaseEntity<CollectUse> useBase = gson.fromJson(s, useType);
                            updateList(useBase.getData().getList());
                        } else {
                            ToastUtil.showToast(base.getMsg());
                        }
                    }
                });

    }

    private void updateList(List<IpModelEntity> ipModelEntities) {
        number++;
        for (IpModelEntity ipModel : ipModelEntities) {
            mIpModelList.add(ipModel);
        }
        mIpModelAdapter.notifyDataSetChanged();
    }


}